<template>
  <div>
    <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }" :form="form">
      <a-card title="商家信息" class="mb20">
        <div class="ant-card-content">
          <a-row>
            <a-col :span="12">
              <a-form-item label="商家名称">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'merchantName',
                    { rules: [{ required: true, message: '请输入商家名称' }] },
                  ]"
                  placeholder="请输入商家名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="经营项目及规模">
                <a-select
                  :disabled="ModalType == 'view'"
                  style="width: 47%"
                  v-decorator="[
                    'merchantItems',
                    { rules: [{ required: true, message: '请选择经营项目' }] },
                  ]"
                  placeholder="请选择经营项目"
                >
                  <a-select-option
                    v-for="(item, index) in merchantItems"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
                <a-input
                  :disabled="ModalType == 'view'"
                  class="ml20"
                  style="width: 47%"
                  v-decorator="[
                    'merchantScale',
                    { rules: [{ required: true, message: '请输入规模' }] },
                  ]"
                  placeholder="规模"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="商家状态">
                <a-radio-group
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'merchantStatus',
                    { rules: [{ required: true, message: '请商家状态' }] },
                  ]"
                >
                  <a-radio :value="0"> 歇业 </a-radio>
                  <a-radio :value="1"> 营业 </a-radio>
                  <a-radio :value="2"> 装修 </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="实际经营项目">
                <a-select
                  :disabled="ModalType == 'view'"
                  style="width: 100%"
                  v-decorator="[
                    'actualBusinessItems',
                    {
                      rules: [
                        { required: true, message: '请选择实际经营项目' },
                      ],
                    },
                  ]"
                  placeholder="请选择实际经营项目"
                >
                  <a-select-option
                    v-for="(item, index) in merchantItems"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="商家位置">
                <div class="flex">
                  <a-select
                    :disabled="ModalType == 'view'"
                    style="width: 160px; margin-left: 10px"
                    placeholder="请选择街道"
                    allowClear
                    show-search
                    @change="handleChangeRoad"
                    v-decorator="['road', { rules: [{ required: false }] }]"
                  >
                    <a-select-option v-for="d in roadList" :key="d.baseStreet">
                      {{ d.baseStreet }}
                    </a-select-option>
                  </a-select>
                  <a-select
                    :disabled="ModalType == 'view'"
                    style="width: 160px; margin-left: 10px"
                    placeholder="请选择巷段"
                    allowClear
                    show-search
                    v-decorator="[
                      'community',
                      { rules: [{ required: false }] },
                    ]"
                    @change="handleChangeCommunity"
                  >
                    <a-select-option
                      v-for="d in communityList"
                      :key="d.baseLine"
                    >
                      {{ d.baseLine }}
                    </a-select-option>
                  </a-select>
                  <a-select
                    :disabled="ModalType == 'view'"
                    style="width: 160px; margin-left: 10px"
                    placeholder="请选择门牌号"
                    allowClear
                    mode="tags"
                    show-search
                    :maxTagCount="1"
                    v-decorator="[
                      'houseNumber',
                      { rules: [{ required: false }] },
                    ]"
                  >
                    <a-select-option
                      v-for="d in houseNumberList"
                      :key="d.baseDetail"
                    >
                      {{ d.baseDetail }}
                    </a-select-option>
                  </a-select>
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="经营类型">
                <a-select
                  :disabled="ModalType == 'view'"
                  style="width: 100%"
                  v-decorator="[
                    'merchantType',
                    { rules: [{ required: true, message: '请选择经营类型' }] },
                  ]"
                  placeholder="请选择经营类型"
                >
                  <a-select-option
                    v-for="(item, index) in merchantList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-card>
      <a-card title="人员信息" class="mb20">
        <div class="ant-card-content">
          <a-row>
            <a-col :span="12">
              <a-form-item label="房东姓名">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'landlordName',
                    { rules: [{ required: true, message: '请输入房东姓名' }] },
                  ]"
                  placeholder="请输入房东姓名"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="经营者姓名">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'operatorName',
                    {
                      rules: [{ required: true, message: '请输入经营者姓名' }],
                    },
                  ]"
                  placeholder="请输入经营者姓名"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="房东联系方式">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'landlordContact',
                    {
                      rules: [
                        { required: true, message: '请输入房东联系方式' },
                      ],
                    },
                  ]"
                  placeholder="请输入房东联系方式"
                />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="经营者联系方式">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'operatorContact',
                    { rules: [{ required: true, message: '经营者联系方式' }] },
                  ]"
                  placeholder="经营者联系方式"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="承租人姓名">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'tenantName',
                    { rules: [{ required: true, message: '承租人姓名' }] },
                  ]"
                  placeholder="承租人姓名"
                />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="经营者籍贯">
                <a-tree-select
                  :disabled="ModalType == 'view'"
                  show-search
                  style="width: 100%"
                  v-decorator="[
                    'operatorHometownCity',
                    {
                      rules: [{ required: true, message: '请选择经营者籍贯' }],
                    },
                  ]"
                  @change="changeAdd"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择经营者籍贯"
                  allow-clear
                  :treeData="allAdd"
                  :replaceFields="{
                    title: 'label',
                    children: 'children',
                    value: 'value',
                  }"
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="承租人联系方式">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'tenantContact',
                    { rules: [{ required: true, message: '承租人联系方式' }] },
                  ]"
                  placeholder="承租人联系方式"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="经营者民族">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'operatorEthnicity',
                    { rules: [{ required: true, message: '经营者民族' }] },
                  ]"
                  placeholder="经营者民族"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="承租人政治面貌">
                <a-select
                  :disabled="ModalType == 'view'"
                  style="width: 100%"
                  v-decorator="[
                    'tenantPoliticalStatus',
                    { rules: [{ required: true, message: '承租人政治面貌' }] },
                  ]"
                  placeholder="承租人政治面貌"
                >
                  <a-select-option
                    v-for="(item, index) in politicalList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.value }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="经营者政治面貌">
                <a-select
                  :disabled="ModalType == 'view'"
                  style="width: 100%"
                  v-decorator="[
                    'operatorPoliticalStatus',
                    { rules: [{ required: true, message: '经营者政治面貌' }] },
                  ]"
                  placeholder="经营者政治面貌"
                >
                  <a-select-option
                    v-for="(item, index) in politicalList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.value }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="承租人入党时间">
                <a-date-picker
                  style="width: 100%"
                  :disabled="ModalType == 'view'"
                  show-time
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择上报时间"
                  v-decorator="['tenantPartyJoinDate']"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="经营者入党时间">
                <a-date-picker
                  :disabled="ModalType == 'view'"
                  show-time
                  style="width: 100%"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择上报时间"
                  v-decorator="['operatorPartyJoinDate']"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12"> </a-col>
            <a-col :span="12">
              <a-form-item label="经营者入党所在组织">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="['operatorPartyOrganization']"
                  placeholder="请输入经营者入党所在组织"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-card>
      <a-card title="建筑信息" class="mb20">
        <div class="ant-card-content">
          <a-row>
            <a-col :span="12">
              <a-form-item label="场所面积">
                <a-input
                  :disabled="ModalType == 'view'"
                  v-decorator="[
                    'premisesArea',
                    { rules: [{ required: true, message: '请输入场所面积' }] },
                  ]"
                  placeholder="请输入场所面积"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="外部照片">
                <Upload
                  :imageUrl="exteriorPhotoLink"
                  @getImg="getImgW"
                ></Upload>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="内部照片">
                <Upload
                  :imageUrl="interiorPhotoLink"
                  @getImg="getImgN"
                ></Upload>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div style="width: 100%; display: flex; justify-content: center">
          <div style="display: flex; gap: 20px">
            <a-button @click="cancel">取 消</a-button>
            <a-button v-if="ModalType != 'view'" type="primary" @click="save(0)"
              >暂 存</a-button
            >
            <a-button v-if="ModalType != 'view'" type="primary" @click="save(1)"
              >保 存</a-button
            >
          </div>
        </div>
      </a-card>
    </a-form>
  </div>
</template>
<script>
import Upload from "@/component/upload/index.vue";
import dictMixin from "@/mixins/dictMixin.js";
import dayjs from "dayjs";
import { message, Modal } from "ant-design-vue";
import cityJson from "../../../api/city.js";
export default {
  components: {
    Upload,
  },
  mixins: [dictMixin],
  data() {
    return {
      merchantId: "",
      exteriorPhotoLink: "",
      interiorPhotoLink: "",
      addressList: [],
      addressList2: [],
      politicalList: [
        {
          value: "共青团员",
          label: "共青团员",
        },
        {
          value: "预备党员",
          label: "预备党员",
        },
        {
          value: "中共党员",
          label: "中共党员",
        },
      ],
      merchantItems: [
        {
          value: "住宿服务",
          label: "住宿服务",
          children: [],
        },
      ],
      form: this.$form.createForm(this, { name: "coordinated" }),
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
      },
      formTailLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19, offset: 4 },
      },
      ModalType: "",
      allAdd: [],
      roadList: [],
      communityList: [],
      houseNumberList: [],
      formInfo: {},
    };
  },
  created() {
    // this.getTree();
    this.getRoadData();
    this.operatorHometown();
    if (this.$route.query.merchantId) {
      this.getDetail(this.$route.query.merchantId);
      this.ModalType = this.$route.query.type;
      this.merchantId = this.$route.query.merchantId;
    }
    // 获取商家类型数据
    this.getSpecialDictData({
      code: "merchant_code", // 商家类型
      name: "merchantList",
    });
  },
  methods: {
    // 事发路段
    getRoadData() {
      this.$axios
        .post("/government-platform-center/case/getAddressArea")
        .then((res) => {
          if (res.data.code === 0) {
            // 使用formatRoadData处理数据
            this.roadList = res.data.data;
          }
        });
    },
    // 获取巷段
    handleChangeRoad(val) {
      const params = new URLSearchParams();
      this.form.setFieldsValue({
        community: undefined,
        houseNumber: undefined,
      });
      this.houseNumberList = [];
      params.append("area", val);
      this.$axios
        .post("/government-platform-center/case/getAddressStreet", params)
        .then((res) => {
          if (res.data.code === 0) {
            this.communityList = res.data.data;
          }
        });
    },
    // 获取门牌号
    async handleChangeCommunity(val) {
      this.form.setFieldsValue({
        houseNumber: undefined,
      });

      try {
        // 等待获取表单值
        // const formValues = await this.getFormValues(); // 这里讲道理不需要校验是否填了，直接获取绑定的值
        const params = new URLSearchParams();
        params.append("area", this.form.getFieldValue("road"));
        params.append("street", val);

        const res = await this.$axios.post(
          "/government-platform-center/case/getAddressNumber",
          params
        );

        if (res.data.code === 0) {
          // 使用formatRoadData处理数据
          this.houseNumberList = res.data.data;
        } else {
          this.$message.error(res.data.msg || "获取门牌号失败");
        }
      } catch (error) {
        console.error("获取门牌号时出错:", error);
        this.$message.error("获取门牌号时出错");
      }
    },
    // 获取街道
    getAddressArea() {
      var q1 = "government-platform-center/case/getAddressArea";
      this.$axios.post(q1).then((res) => {
        if (res.data.msg == "success") {
          var data = res.data.data;
          // console.log('---',data)

          this.fzroptions = [];
          for (let i = 0; i < data.length; i++) {
            // console.log('---',data[i])
            this.fzroptions.push({
              value: data[i].baseStreet,
              label: data[i].baseStreet,
              // children: [],
              isLeaf: false,
            });
          }
          console.log("--------", this.fzroptions);
        }
      });
    },
    async loadData(selectedOptions) {
      console.log("selectedOptions", selectedOptions);
      const targetNode0 = selectedOptions[0]; //第一条
      const targetNode = selectedOptions[selectedOptions.length - 1];
      targetNode.loading = true;

      try {
        // 模拟异步请求（根据当前节点层级返回不同数据）
        const children = await this.mockApi(
          targetNode.value,
          selectedOptions.length,
          targetNode0
        );

        // 关键：使用 Vue.set 确保响应式更新
        this.$set(targetNode, "children", children);
      } catch (error) {
        console.error("加载失败:", error);
      } finally {
        targetNode.loading = false;
      }
    },

    // 模拟 API 返回数据（实际替换为你的接口）
    mockApi(parentId, level, targetNode0) {
      // console.log('当前选择',parentId)
      return new Promise((resolve) => {
        if (level === 1) {
          // 加载二级数据（市）
          const q = "government-platform-center/case/getAddressStreet";
          this.$axios
            .post(
              q,
              { area: parentId },
              {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              }
            )
            .then((res) => {
              if (res.data.msg === "success") {
                const children = res.data.data.map((item) => ({
                  label: item.baseLine,
                  value: item.baseLine,
                  isLeaf: false, // 二级节点仍需加载三级数据
                }));
                resolve(children); // 关键：在接口回调中 resolve
              } else {
                resolve([]); // 失败返回空数组
              }
            })
            .catch((error) => {
              // console.error("接口请求失败:", error);
              resolve([]);
            });
        } else if (level === 2) {
          // 加载三级数据（区）- 这里也需要替换为真实接口
          const q = "government-platform-center/case/getAddressNumber";
          this.$axios
            .post(
              q,
              { street: parentId, area: targetNode0.value },
              {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              }
            )
            .then((res) => {
              if (res.data.msg === "success") {
                const children = res.data.data.map((item) => ({
                  label: item.baseDetail,
                  value: item.baseDetail,
                  isLeaf: true, // 三级节点为叶子节点
                }));
                resolve(children);
              } else {
                resolve([]);
              }
            })
            .catch((error) => {
              // console.error("接口请求失败:", error);
              resolve([]);
            });
        }
      });
    },

    selectFzr(e) {
      console.log(e);
      if (e.length == 1) {
        this.valueLoadData1 = e[0];
        this.community = e[0];
      }
      if (e.length == 2) {
        this.valueLoadData1 = this.community + e[1];
        this.road = e[1];
      }
      if (e.length == 3) {
        this.valueLoadData1 = this.community + this.road + e[2];
        this.houseNumber = e[2];
      }
    },

    handleSearchRoad(input) {
      // 检查是否已有匹配的选项
      const hasMatch = this.addressList.some((option) =>
        option.name.toLowerCase().includes(input.toLowerCase())
      );

      // 如果没有匹配的选项且输入不为空，添加新选项
      if (!hasMatch && input.trim()) {
        const newOption = {
          value: `new-${input}`,
          name: input,
        };
        this.addressList.push(newOption);
      }
    },
    // 获取籍贯
    operatorHometown() {
      let dataCity = cityJson;
      let arr = [];
      for (let i = 0; i < dataCity.length; i++) {
        let son = [];
        // console.log('处理后的地址',dataCity[i])

        if (dataCity[i].city && dataCity[i].city.length > 0) {
          for (let index in dataCity[i].city) {
            if (dataCity[i].city[index].name == "市辖区") {
              son.push({ label: dataCity[i].name, value: dataCity[i].name });
            } else {
              son.push({
                label: dataCity[i].city[index].name,
                value: dataCity[i].city[index].name,
              });
            }
          }
        }
        arr.push({
          label: dataCity[i].name,
          value: dataCity[i].name,
          children: son,
        });
      }
      this.allAdd = arr;
      console.log("处理后的地址", arr);
    },
    getTree() {
      const url = `/government-platform-center/case/getAddressArea`;
      const data = { areaCode: "MERCHANT_LOCATION_CODE" };
      this.$axios.post(url, data).then((res) => {
        if (res.data.code == 0) {
          this.addressList = res.data.data;
        }
      });
      const data2 = { areaCode: "NATIVE_PLACE_CODE" };
      this.$axios.post(url, data2).then((res) => {
        if (res.data.code == 0) {
          this.addressList2 = res.data.data;
        }
      });
    },
    changeDept(e) {
      console.log(e);
    },
    changeAdd(value, label, extra) {
      console.log(value, label, extra);
    },
    getImgW(e) {
      this.exteriorPhotoLink = e;
    },
    getImgN(e) {
      this.interiorPhotoLink = e;
    },
    cancel() {
      this.$router.push({
        path: "/xuncha/sjgl/sjxx",
      });
    },
    save(type) {
      console.log(this.form.getFieldsValue(), "this.form.getFieldsValue()");
      this.form.validateFields((err, values) => {
        console.log(values, "values");
        if (err) {
          return;
        }
        if (!this.merchantId) {
          //const url = "/government-platform-center//xunjian/merchantInfo/add";
          const url = "/government-platform-center/xunjian/merchantInfo/add";
          var form = {
            ...values,
            status: type,
            exteriorPhotoLink: this.exteriorPhotoLink,
            interiorPhotoLink: this.interiorPhotoLink,
            houseNumber:
              values.houseNumber && values.houseNumber.length > 0
                ? values.houseNumber[0]
                : "",
          };
          this.$axios.post(url, form).then((res) => {
            //interiorPhotoLink;
            if (res.data.code == 0) {
              this.dialogVisible = false;
              let title = type == 0 ? "暂存" : "保存";
              message.success(`${title}成功`);
            }
          });
        } else {
          const url = "/government-platform-center/xunjian/merchantInfo/edit";
          var form = {
            ...values,
            merchantId: this.merchantId,
            status: type,
            exteriorPhotoLink: this.exteriorPhotoLink,
            interiorPhotoLink: this.interiorPhotoLink,
            houseNumber:
              values.houseNumber && values.houseNumber.length > 0
                ? values.houseNumber[0]
                : "",
          };
          this.$axios.post(url, form).then((res) => {
            if (res.data.code == 0) {
              this.dialogVisible = false;
              message.success("修改成功");
              this.$router.go(-1);
            }
          });
        }
        this.$router.back();
      });
    },
    getDetail(id) {
      const url = `/government-platform-center/xunjian/merchantInfo/detail?merchantId=${id}`;
      this.$axios.get(url).then((res) => {
        if (res.data.code == 0) {
          this.formInfo = res.data.data;
          this.form.setFieldsValue(res.data.data);
          this.exteriorPhotoLink = res.data.data.exteriorPhotoLink || "";
          this.interiorPhotoLink = res.data.data.interiorPhotoLink || "";
          // 获取网格
          if (this.formInfo.road) {
            this.handleChangeRoad(this.formInfo.road);
          }
          if (this.formInfo.community) {
            this.handleChangeCommunity(this.formInfo.community);
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.ant-card-content {
  padding-left: 200px;
}
.ant-form-item-label {
  width: 200px;
}
</style>
